package com.huangliusong.product.service;

import com.huangliusong.product.DTO.CartDTO;
import com.huangliusong.product.dataobject.ProductInfo;
import com.huangliusong.product.enums.ProductStatusEnum;
import com.huangliusong.product.enums.ResultEnum;
import com.huangliusong.product.exception.ProductException;
import com.huangliusong.product.repository.ProductInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * @author huangliusong
 * @since 2018/10/19
 * {@link ProductService}
 */
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private ProductInfoRepository productInfoRepository;
    @Override
    public List<ProductInfo> findUpAll() {
        return productInfoRepository.findByProductStatus(ProductStatusEnum.UP.getCode());
    }

    @Override
    public List<ProductInfo> findList(List<String> productIdList) {
        return productInfoRepository.findByProductIdIn(productIdList);
    }

    @Override
    @Transactional
    public void decreaseStock(List<CartDTO> cartDTOList)  {
        for(CartDTO cartDTO:cartDTOList){
            Optional<ProductInfo> productInfoOptional=productInfoRepository
                    .findById(cartDTO.getProductId());

            //判断商品是否存在
            if (!productInfoOptional.isPresent()){
                throw new ProductException(ResultEnum.PRODUCT_NOT_EXIST);
            }

            //判断库存是否足够
            ProductInfo productInfo=productInfoOptional.get();
            Integer result=productInfo.getProductStock()-cartDTO.getProductQuantity();
            if (result<0){
                throw new ProductException(ResultEnum.PRODUCT_STOCK_ERROR);
            }

            productInfo.setProductStock(result);

            productInfoRepository.save(productInfo);
        }
    }
}
